/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * TreeView.java
 *http://www.jgraph.com/doc/mxgraph/index_javavis.html
 * Created on 30.05.2012, 00:53:26
 */
package treeView;

import interfaceAndController.Controller;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.LayoutManager;
import java.awt.Rectangle;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.antlr.runtime.tree.Tree;
import org.jgraph.JGraph;
import org.jgraph.graph.DefaultGraphCell;
import org.jgraph.graph.Edge;
import org.jgraph.graph.EdgeView;
import org.jgraph.graph.GraphConstants;
import org.jgrapht.ListenableGraph;
import org.jgrapht.ext.JGraphModelAdapter;
import org.jgrapht.graph.DefaultEdge;
import org.jgrapht.graph.ListenableDirectedGraph;


import checkInputType.ReturnAst;

import com.jgraph.layout.JGraphFacade;
import com.jgraph.layout.tree.JGraphTreeLayout;

import findAntlrRules.AntlrRule;
import gettree.TreeNode;

/**
 *http://jgrapht.org/visualizations.html
 * @author daniel
 */
public class TreeView extends javax.swing.JPanel {

	private JGraphModelAdapter m_jgAdapter;
	private ReturnAst currentRet = null; 
	//private JGraph graph = new JGraph();
	/** Creates new form TreeView */
	public TreeView() {
		super();	}

	/** This method is called from within the constructor to
	 * initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is
	 * always regenerated by the Form Editor.
	 */
	@SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        setBackground(new java.awt.Color(255, 255, 255));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );
    }// </editor-fold>//GEN-END:initComponents
    // Variables declaration - do not modify//GEN-BEGIN:variables
    // End of variables declaration//GEN-END:variables


	public void loadTree(TreeNode ret){
		//try{

		this.removeAll();
		if (ret == null)
			return;
		ListenableGraph g = new ListenableDirectedGraph( DefaultEdge.class );
		
		// create a visualization using JGraph, via an adapter
		m_jgAdapter = new JGraphModelAdapter( g );

		JGraph jgraph = new JGraph( m_jgAdapter );

		preorder(g, ret,null);
		//adjustDisplaySettings( jgraph );
		// add some sample data (graph manipulated via JGraphT)
		//  g.addVertex( "v1" );
		//  g.addVertex( "v2" );
		//  g.addVertex( "v3" );
		//  g.addVertex( "v4" );
		// g.addEdge( "v1", "v2" );
		// g.addEdge( "v2", "v3" );

		TreeLayoutAlgorithm tlg = new TreeLayoutAlgorithm();

		tlg.run(jgraph,jgraph.getRoots() , null);

		this.add( jgraph );  



	}

	public void preorder(ListenableGraph g,TreeNode t,TreeWrapper parent){
		try{
			String apprRule = t.getLabel();
			TreeWrapper tw;
			if (t!=null){
				tw = new TreeWrapper();
				if (!apprRule.trim().isEmpty()){
					AntlrRule r = null;
					String rName = apprRule.lastIndexOf('_')==-1?apprRule.trim():apprRule.substring(0,apprRule.lastIndexOf('_')).trim();
					int nr = -1 ;
					try {
						nr = Integer.parseInt(apprRule.split("_")[apprRule.split("_").length-1]);
					}
					catch (Exception e) {
					}
					for (AntlrRule rc :Controller.orderedRuleList){
						if (rc.getName().trim().equals(rName.trim())){
							r = rc ;
							break;
						}
					}
					if (r!=null &&  nr !=-1 && r.getLabels()!=null && r.getLabels().size()>nr)
						if (!r.getLabels().get(nr).trim().isEmpty())
							tw.setLabel(r.getLabels().get(nr));
					tw.setRule(rName);
					tw.setRuleNr(nr);

				}
				tw.setTree(t);
				g.addVertex(tw);
				if (parent!=null)
					g.addEdge(parent, tw);
				
				
			}
			else
				return;
			for (int i = t.getChildCount()-1 ; i>-1  ; i--){
				preorder(g, t.getChild(i),tw);
			}
		}catch (Exception e) {
			int  i = 0 ; i++;
			int  k ;
		}
	}

	private void adjustDisplaySettings( JGraph jg ) {
		jg.setPreferredSize(new Dimension(300, 300) );
		Color  c        = Color.white;
		jg.setBackground( c );
	}

	private void positionVertexAt( Object vertex, int x, int y ) {
		DefaultGraphCell cell = m_jgAdapter.getVertexCell( vertex );
		Map              attr = cell.getAttributes(  );
		Rectangle2D        b    = GraphConstants.getBounds( attr );
		GraphConstants.setBounds( attr, new Rectangle( x, y, (int)b.getWidth(),(int) b.getHeight() ) );
		Map cellAttr = new HashMap(  );
		cellAttr.put( cell, attr );
		m_jgAdapter.edit( cellAttr, null, null, null);
	}
}
